import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/artifacts/auth_portal_dialog.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/artifacts/report_vault_dialog.dart';
import 'package:raze/artifacts/clickable_avatar_widget.dart';
import 'package:raze/artifacts/void_placeholder_widget.dart';
import 'package:raze/lore/chronicle/community_chronicle.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 社区详情页面
class CommunityDetailRealms extends StatefulWidget {
  const CommunityDetailRealms({super.key});

  @override
  State<CommunityDetailRealms> createState() => _CommunityDetailRealmsState();
}

class _CommunityDetailRealmsState extends State<CommunityDetailRealms> {
  final TextEditingController _commentController = TextEditingController();
  final FocusNode _commentFocusNode = FocusNode();

  // 保存社区ID，避免在 build 中重复获取
  late final String _communityId;

  @override
  void initState() {
    super.initState();
    // 在初始化时获取社区ID
    _communityId = Get.parameters['communityId'] ?? '';
  }

  @override
  void dispose() {
    _commentController.dispose();
    _commentFocusNode.dispose();
    super.dispose();
  }

  /// 格式化评论时间（相对时间）
  String _formatCommentTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'Just now';
    }
  }

  @override
  Widget build(BuildContext context) {
    final communityChronicle = Get.find<CommunityChronicle>();
    final userChronicle = Get.find<UserChronicle>();

    // 获取社区详情（使用保存的社区ID）
    final community = communityChronicle.queryCommunityById(_communityId);
    if (community == null) {
      return Scaffold(
        backgroundColor: RazeConstants.background,
        body: Center(
          child:
              Text('Community post not found')
                  .applyTypeSize(16.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans(),
        ),
      );
    }

    // 获取帖子作者
    final author = userChronicle.queryUserById(community.userId);
    // 获取评论列表
    final comments = communityChronicle.fetchComments(_communityId);

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: Stack(
            children: [
              Column(
                children: [
                  // 顶部导航栏
                  _assembleTopNavigationBar(_communityId, communityChronicle),

                  // 主要内容区域（可滚动）
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 帖子图片
                          _constructPostImage(community),

                          // 用户信息和互动指标
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 16.w),
                            child: _assembleUserAndEngagement(
                              author,
                              community,
                              communityChronicle,
                              userChronicle,
                            ),
                          ),

                          // 帖子描述
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 16.w),
                            child: _constructPostDescription(community),
                          ),

                          // 操作按钮和评论按钮
                          Padding(
                            padding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                              vertical: 16.h,
                            ),
                            child: _assembleActionButtons(),
                          ),

                          // 评论列表
                          Container(
                            decoration: BoxDecoration(
                              color: RazeConstants.white,
                              borderRadius: BorderRadius.circular(12.r),
                              border: Border.all(
                                color: RazeConstants.black,
                                width: 1.w,
                              ),
                            ),
                            padding: EdgeInsets.symmetric(
                              horizontal: 12.w,
                              vertical: 6.h,
                            ),
                            margin: EdgeInsets.symmetric(horizontal: 16.w),
                            child:
                                comments.isNotEmpty
                                    ? _constructCommentsList(
                                      comments,
                                      userChronicle,
                                      communityChronicle,
                                    )
                                    : Padding(
                                      padding: EdgeInsets.symmetric(
                                        vertical: 40.h,
                                      ),
                                      child: VoidPlaceholderWidget(
                                        message: 'No comments yet',
                                      ),
                                    ),
                          ),

                          // 底部间距（为固定输入框留出空间）
                          SizedBox(height: 120.h),
                        ],
                      ),
                    ),
                  ),
                ],
              ),

              // 底部固定的评论输入区域（响应式更新登录状态）
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: Obx(() {
                  final userChronicle = Get.find<UserChronicle>();
                  return _constructFixedCommentInput(
                    userChronicle.currentUser,
                    _communityId,
                    communityChronicle,
                  );
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 组装顶部导航栏
  Widget _assembleTopNavigationBar(
    String communityId,
    CommunityChronicle communityChronicle,
  ) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  borderRadius: BorderRadius.circular(8.r),
                  border: Border.all(color: RazeConstants.black, width: 2.w),
                ),
                child: Icon(
                  Icons.chevron_left_rounded,
                  size: 24.sp,
                  color: RazeConstants.black,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(onTap: () => Get.back()),

          // 举报按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  borderRadius: BorderRadius.circular(8.r),
                  border: Border.all(color: RazeConstants.black, width: 2.w),
                ),
                padding: EdgeInsets.all(3.w),
                child: Image.asset('assets/images/report2.png'),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(
                onTap: () {
                  ReportVaultDialog.revealReportVault(
                    onReportSubmitted: (_) {
                      NotifierGlimmer.revealInfo(
                        'Report submitted successfully.',
                      );
                      communityChronicle.deleteCommunityById(communityId);
                      Get.back();
                    },
                  );
                },
              ),
        ],
      ),
    );
  }

  /// 构建帖子图片
  Widget _constructPostImage(dynamic community) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: RazeConstants.black, width: 2.w),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10.r),
        child: AspectRatio(
          aspectRatio: 343 / 205,
          child:
              community.contentType == 'video'
                  ? GestureDetector(
                    onTap: () {
                      // 跳转到视频播放页面
                      Get.toNamed(
                        '/video-player',
                        parameters: {'videoPath': community.media},
                      );
                    },
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        // 视频封面
                        Image.asset(
                          community.coverImage ?? community.media,
                          fit: BoxFit.cover,
                        ),
                        // 播放图标
                        Center(
                          child: // 播放图标
                              Container(
                            width: 56.w,
                            height: 56.w,
                            decoration: BoxDecoration(
                              color: RazeConstants.white.withOpacity(0.9),
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: RazeConstants.black,
                                width: 2.w,
                              ),
                            ),
                            child: Icon(
                              Icons.play_arrow_rounded,
                              size: 36.w,
                              color: RazeConstants.black,
                            ),
                          ).withRightBottomShadow(thickness: 1.5),
                        ),
                      ],
                    ),
                  )
                  : Image.asset(community.media, fit: BoxFit.cover),
        ),
      ),
    ).withRightBottomShadow(thickness: 1.5);
  }

  /// 组装用户信息和互动指标
  Widget _assembleUserAndEngagement(
    dynamic author,
    dynamic community,
    CommunityChronicle communityChronicle,
    UserChronicle userChronicle,
  ) {
    // 统计评论数
    final commentCount = communityChronicle.fetchComments(community.id).length;

    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        // 用户头像
        ClickableAvatarWidget(
          userId: author?.id ?? '',
          avatarPath: author?.avatar ?? 'assets/images/avatar1.png',
          width: 40.w,
          height: 40.w,
        ),
        12.w.boxWidth,

        // 用户名和互动指标
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户名
              Text(author?.username ?? 'Unknown')
                  .applyTypeSize(16.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans(weight: FontWeight.w500),
              2.h.boxHeight,
              // 互动指标
              Row(
                children: [
                  // 评论数
                  Row(
                    children: [
                      Image.asset(
                        'assets/images/community-comment.png',
                        width: 16.w,
                        height: 16.w,
                      ),
                      4.w.boxWidth,
                      Text('$commentCount')
                          .applyTypeSize(14.sp)
                          .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                          .applyNotoSans(),
                    ],
                  ),
                  8.w.boxWidth,
                  // 点赞数（不可点击，但实时更新）
                  Row(
                    children: [
                      Image.asset(
                        'assets/images/community-like.png',
                        width: 16.w,
                        height: 16.w,
                      ),
                      4.w.boxWidth,
                      Obx(() {
                        final updatedCommunity = communityChronicle
                            .queryCommunityById(community.id);
                        return Text('${updatedCommunity?.likeCount ?? 0}')
                            .applyTypeSize(14.sp)
                            .applyTypeColor(
                              RazeConstants.black.withOpacity(0.6),
                            )
                            .applyNotoSans();
                      }),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),

        // 操作按钮（点赞和人物）
        Row(
          children: [
            // 点赞按钮（带底层盒子）
            SizedBox(
              width: 40.w,
              height: 40.w,
              child: Stack(
                clipBehavior: Clip.none,
                children: [
                  // 底层盒子（右下角偏移）
                  Positioned(
                    top: 4.w,
                    left: 4.w,
                    right: -4.w,
                    bottom: -4.w,
                    child: Container(
                      decoration: BoxDecoration(
                        color: RazeConstants.darkYellow,
                        borderRadius: BorderRadius.circular(6.r),
                        border: Border.all(
                          color: RazeConstants.black,
                          width: 1.w,
                        ),
                      ),
                    ),
                  ),

                  // 点赞按钮
                  Obx(() {
                    final currentUser = userChronicle.currentUser;
                    final liked =
                        currentUser != null &&
                        communityChronicle.checkCommunityLiked(
                          currentUser.id,
                          community.id,
                        );
                    return Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                        color:
                            liked ? RazeConstants.yellow : RazeConstants.yellow,
                        borderRadius: BorderRadius.circular(6.r),
                        border: Border.all(
                          color: RazeConstants.black,
                          width: 1.w,
                        ),
                      ),
                      padding: EdgeInsets.all(8.w),
                      child: Image.asset(
                        liked
                            ? 'assets/images/like.png'
                            : 'assets/images/unlike.png',
                        color: liked ? RazeConstants.red : RazeConstants.black,
                      ),
                    ).withTouchResonance(
                      onTap: () {
                        if (currentUser == null) {
                          AuthPortalDialog.revealAuthPortal();
                          return;
                        }

                        final hasLiked = communityChronicle.checkCommunityLiked(
                          currentUser.id,
                          community.id,
                        );
                        if (hasLiked) {
                          communityChronicle.unlikeCommunity(
                            currentUser.id,
                            community.id,
                          );
                        } else {
                          communityChronicle.likeCommunity(
                            currentUser.id,
                            community.id,
                          );
                        }
                      },
                    );
                  }),
                ],
              ),
            ),
            12.w.boxWidth,

            // 人物按钮（带底层盒子）
            SizedBox(
              width: 40.w,
              height: 40.w,
              child: Stack(
                clipBehavior: Clip.none,
                children: [
                  // 底层盒子（右下角偏移）
                  Positioned(
                    top: 4.w,
                    left: 4.w,
                    right: -4.w,
                    bottom: -4.w,
                    child: Container(
                      decoration: BoxDecoration(
                        color: RazeConstants.grey,
                        borderRadius: BorderRadius.circular(6.r),
                        border: Border.all(
                          color: RazeConstants.black,
                          width: 1.w,
                        ),
                      ),
                    ),
                  ),

                  // 人物按钮
                  Container(
                    width: 40.w,
                    height: 40.w,
                    decoration: BoxDecoration(
                      color: RazeConstants.white,
                      borderRadius: BorderRadius.circular(6.r),
                      border: Border.all(
                        color: RazeConstants.black,
                        width: 1.w,
                      ),
                    ),
                    padding: EdgeInsets.all(8.w),
                    child: Image.asset('assets/images/person.png'),
                  ).withTouchResonance(onTap: () {}),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建帖子描述
  Widget _constructPostDescription(dynamic community) {
    return Padding(
      padding: EdgeInsets.only(top: 12.h),
      child: Text(community.detail)
          .applyTypeSize(14.sp)
          .applyTypeColor(RazeConstants.black)
          .applyNotoSans(weight: FontWeight.w400),
    );
  }

  /// 组装操作按钮
  Widget _assembleActionButtons() {
    return SizedBox(
      height: 38.h,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 底层盒子（右下角偏移）
          Positioned(
            top: 4.w,
            left: 4.w,
            right: -4.w,
            bottom: -4.w,
            child: Container(
              decoration: BoxDecoration(
                color: RazeConstants.darkYellow,
                borderRadius: BorderRadius.circular(6.r),
                border: Border.all(color: RazeConstants.black, width: 2.w),
              ),
            ),
          ),

          // 评论按钮
          Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
            decoration: BoxDecoration(
              color: RazeConstants.yellow,
              borderRadius: BorderRadius.circular(6.r),
              border: Border.all(color: RazeConstants.black, width: 2.w),
            ),
            child: Text('Comment')
                .applyTypeSize(18.sp)
                .applyTypeColor(RazeConstants.black)
                .applyNotoSans(weight: FontWeight.w600),
          ).withTouchResonance(
            onTap: () {
              // 聚焦到输入框
              _commentFocusNode.requestFocus();
            },
          ),
        ],
      ),
    );
  }

  /// 构建评论列表
  Widget _constructCommentsList(
    List comments,
    UserChronicle userChronicle,
    CommunityChronicle communityChronicle,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        16.h.boxHeight,
        ...comments.map((comment) {
          final commentUser = userChronicle.queryUserById(comment.userId);
          return _constructCommentItem(
            comment,
            commentUser,
            communityChronicle,
          );
        }),
      ],
    );
  }

  /// 构建单个评论项
  Widget _constructCommentItem(
    dynamic comment,
    dynamic commentUser,
    CommunityChronicle communityChronicle,
  ) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 评论者头像
          ClickableAvatarWidget(
            userId: commentUser?.id ?? '',
            avatarPath: commentUser?.avatar ?? 'assets/images/avatar1.png',
            width: 40.w,
            height: 40.w,
          ),
          12.w.boxWidth,
          // 评论内容
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    // 用户名
                    Expanded(
                      child: Text(commentUser?.username ?? 'Unknown')
                          .applyTypeSize(16.sp)
                          .applyTypeColor(RazeConstants.black)
                          .applyNotoSans(weight: FontWeight.w700),
                    ),
                    // 举报按钮
                    GestureDetector(
                      onTap: () {
                        ReportVaultDialog.revealReportVault(
                          onReportSubmitted: (_) {
                            NotifierGlimmer.revealInfo(
                              'Report submitted successfully.',
                            );
                            // 删除评论
                            communityChronicle.eraseCommentById(comment.id);
                            // 刷新页面
                            setState(() {});
                          },
                        );
                      },
                      child: Image.asset(
                        'assets/images/report.png',
                        width: 16.w,
                        height: 16.w,
                      ),
                    ),
                  ],
                ),
                4.h.boxHeight,
                Text(comment.content)
                    .applyTypeSize(13.sp)
                    .applyTypeColor(Colors.black.withValues(alpha: 0.70))
                    .applyNotoSans(weight: FontWeight.w400),
                4.h.boxHeight,
                // 时间（右下角）
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(_formatCommentTime(comment.createTime))
                        .applyTypeSize(12.sp)
                        .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                        .applyNotoSans(),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建固定的评论输入区域
  Widget _constructFixedCommentInput(
    dynamic currentUser,
    String communityId,
    CommunityChronicle communityChronicle,
  ) {
    return Container(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 44.h),
      decoration: BoxDecoration(color: Colors.transparent),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 输入框（发送按钮在内部右边）
          Container(
            padding: EdgeInsets.only(right: 8.w),
            decoration: BoxDecoration(
              color: RazeConstants.background,
              borderRadius: BorderRadius.circular(12.r),
              border: Border.all(
                color: RazeConstants.black.withOpacity(0.3),
                width: 1.w,
              ),
            ),
            child: Row(
              children: [
                // 输入框
                Expanded(
                  child: TextField(
                    controller: _commentController,
                    focusNode: _commentFocusNode,
                    decoration: InputDecoration(
                      hintText: 'Input Content',
                      hintStyle: TextStyle(
                        fontSize: 14.sp,
                        color: RazeConstants.black.withOpacity(0.5),
                        fontFamily: 'NotoSans',
                      ),
                      border: InputBorder.none,
                      isDense: true,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                    ),
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: RazeConstants.black,
                      fontFamily: 'NotoSans',
                    ),
                  ),
                ),

                // 发送按钮（在输入框内部右边）
                Container(
                  width: 30.w,
                  height: 30.w,
                  decoration: BoxDecoration(
                    color: RazeConstants.yellow,
                    borderRadius: BorderRadius.circular(6.r),
                    border: Border.all(color: RazeConstants.black, width: 1.w),
                  ),
                  padding: EdgeInsets.all(3.w),
                  child: Image.asset('assets/images/send.png'),
                ).withTouchResonance(
                  onTap: () {
                    if (currentUser == null) {
                      AuthPortalDialog.revealAuthPortal();
                      return;
                    }

                    final content = _commentController.text.trim();
                    if (content.isEmpty) {
                      return;
                    }

                    // 提交评论
                    communityChronicle.postComment(
                      communityId,
                      currentUser.id,
                      content,
                    );

                    // 清空输入框
                    _commentController.clear();

                    // 收起键盘
                    _commentFocusNode.unfocus();

                    // 提示
                    NotifierGlimmer.revealInfo('Comment posted successfully.');

                    // 刷新页面
                    setState(() {});
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
